package com.bw.controller;

import com.bw.domain.BResult;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@RestController
public class UploadController {



    @RequestMapping("/uploadPic")
    public BResult flag(MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        //1. 校验图片的格式
        String contentType = file.getContentType();
        if (!contentType.equals("image/jpeg")){
            return BResult.error("图片格式必须是image/jpeg ");
        }
        //2. 校验图片的格式  小于 2M
        long size = file.getSize();
        long m = size / 1024 / 1024;
        if (m >2){
            return BResult.error("图片的格式  小于 2M");
        }

        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint("http://127.0.0.1:9000")
                        .credentials("mwHOdswYUfv4nJr8n555", "jIeOP6ILkyJYAZN7ujPmznrA9LP7ioIO3415Z8Us")
                        .build();

        // 新的文件名
        String filename = UUID.randomUUID() + file.getOriginalFilename();

        minioClient.putObject(
                PutObjectArgs.builder().bucket("my-test01").object(filename).stream(
                                file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());



        return BResult.success("http://127.0.0.1:9000/my-test01/" + filename);
    }
}
